package com.zty.controller;

import com.google.code.kaptcha.Producer;
import com.zty.controller.request.SendCodeRequest;
import com.zty.enums.BizCodeEnum;
import com.zty.enums.SendCodeEnum;
import com.zty.service.NotifyService;
import com.zty.util.CommonUtil;
import com.zty.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ZTY
 * @describe
 * @time 2024-01-22 23:55
 * @projectName zty-short-url
 */
@RestController
@RequestMapping("/api/account/v1")
@Slf4j
public class NotifyController {

    private final static long CAPTCHA_CODE_EXPIRED = 1000 * 10 * 60;

    private final static String MODULE_NAME = "ACCOUNT-SERVER";

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){

        String text = captchaProducer.createText();
        log.info("验证码的内容为：【{}】",text);

        // 将验证码存入redis，设置过期时间10分钟
        redisTemplate.opsForValue().set(getCaptchaKey(request),text,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage image = captchaProducer.createImage(text);

        //  try-with-resource语法可以将流自动关闭（前提是该流要实现AutoCloseable接口）
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取流出错【{}】",e.getMessage());
        }
    }

    /**
     * 发送验证码接口
     * @return
     */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest,HttpServletRequest request){

        //  从redis中获取对应的value
        String key = getCaptchaKey(request);
        String value = redisTemplate.opsForValue().get(key);

        //  获取用户端输入的验证码
        String captcha = sendCodeRequest.getCaptcha();

        if (captcha != null && value.equalsIgnoreCase(captcha)){
            //  成功则删除redis中的内容
            redisTemplate.delete(key);

            //  发送短信验证码
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER,sendCodeRequest.getTo());
        }else {
            //  抛出验证码失败异常
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }

        return JsonData.buildSuccess();
    }

    /**
     * 获取验证码的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){

        //  获取ip地址
        String ipAddr = CommonUtil.getIpAddr(request);
        log.info("客户端ip地址为：【{}】",ipAddr);

        //  获取浏览器指纹（这里只用User-Agent）
        String userAgent = request.getHeader("User-Agent");
        log.info("客户端浏览器指纹为：【{}】",userAgent);

        //  将二者拼接起来
        //  String key = MODULE_NAME + "-CAPTCHA-" + CommonUtil.MD5(ipAddr + userAgent);
        String key = MODULE_NAME + "-CAPTCHA-" + CommonUtil.MD5("172.29.236.41" + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");

        log.info("验证码的key为：【{}】",key);
        return key;
    }

}
